package com.du.User.controller;

import com.du.User.pojo.User;
import com.du.User.service.UserService;
import com.du.common.vo.Result;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ResponseBody
    public String findAll() {
        List<User> users = userService.findAll();
        if (users != null) {
            return "ok";
        }
        return "fail";
    }

    @PostMapping("/login")
    public Result login(User param, HttpSession session, @RequestParam("captcha") String captcha, HttpServletRequest request) {
        //验证码判断
        if (!CaptchaUtil.ver(captcha, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return Result.fail("验证码错误！");
        }
        User user = userService.login(param);
        if (user != null) {
//            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//            boolean matches = passwordEncoder.matches(param.getPassword(),user.getPassword());
//            if (matches) {
                user.setPassword(null);
                session.setAttribute("loginUser", user);
                return Result.success();
//            }

        }
        return Result.fail("用户名或密码错误！");
    }


}
